/**
 * Copyright 1999-2015 dangdang.com.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */

package spring.cloud.tasks.api.controller;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import spring.cloud.tasks.api.domain.NameSpace;
import spring.cloud.tasks.api.domain.NameSpaceConfiguration;
import spring.cloud.tasks.api.domain.ZooKeeperCluster;
import spring.cloud.tasks.api.service.NameSpaceZooKeeperClusterMappingService;
import spring.cloud.tasks.api.service.ZooKeeperService;
import spring.cloud.tasks.api.utils.Response;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("/api")
public class NameSpaceZooKeeperClusterMappingController {

    private static final String EXPORT_FILE_NAME = "namespace_info.xls";

    @Resource
    private NameSpaceZooKeeperClusterMappingService nameSpaceZooKeeperClusterMappingService;
    @Resource
    private ZooKeeperService zooKeeperService;

    /**
     * 创建域
     */
    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    //@Audit
    @PostMapping(value = "/createNameSpace")
    public Response createNameSpace(@RequestParam String nameSpace,
                                    @RequestParam String zooKeeperClusterKey) throws RuntimeException {
        //assertIsPermitted(PermissionKeys.registryCenterAddNamespace);
        NameSpace namespaceInfo = new NameSpace();
        namespaceInfo.setNameSpace(nameSpace);
        namespaceInfo.setZooKeeperClusterKey(zooKeeperClusterKey);
        namespaceInfo.setContent("");
        zooKeeperService.createNameSpace(namespaceInfo);
        return new Response();
    }


    /**
     * 获取所有域列表
     */
    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    @GetMapping(value = "/namespaces/getNameSpaceConfigurationList")
    public Response getNameSpaceConfigurationList() {
        List<NameSpaceConfiguration> nameSpaceConfigurationList = Lists.newLinkedList();
        List<ZooKeeperCluster> zooKeeperClusterList = zooKeeperService.getZooKeeperClusterList();
        for (ZooKeeperCluster zooKeeperCluster : zooKeeperClusterList) {
            if (!zooKeeperCluster.isOffline()) {
                nameSpaceConfigurationList.addAll(zooKeeperCluster.getNameSpaceConfigurationList());
            } else {
                List<NameSpaceConfiguration> list = zooKeeperService.findConfigsByZkCluster(zooKeeperCluster);
                if (list != null && !list.isEmpty()) {
                    nameSpaceConfigurationList.addAll(list);
                }
            }
        }

        return Response.success(nameSpaceConfigurationList);
    }


    /**
     * 刷新注册中心
     */
    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    //@Audit
    @RequestMapping(value = "/registryCenter/notifyRefresh", method = {RequestMethod.GET, RequestMethod.POST})
    public Response notifyRefresh() throws RuntimeException {
        //assertIsPermitted(PermissionKeys.registryCenterAddNamespace);
        zooKeeperService.notifyRefresh();
        return new Response();
    }


    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    //@Audit
    @PostMapping(value = "/createZooKeeperClusterInfo")
    public Response createZooKeeperClusterInfo(@RequestParam String zkClusterKey,
                                               @RequestParam String alias,
                                               @RequestParam String connectString,
                                               @RequestParam(required = false) String description)
            throws RuntimeException {
        //assertIsPermitted(PermissionKeys.registryCenterAddZkCluster);
        zooKeeperService.createZooKeeperClusterInfo(zkClusterKey, alias, connectString.trim(), description);
        return new Response();
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    //@Audit
    @PutMapping(value = "/zkClusters")
    public Response updateZkCluster(@RequestParam String zooKeeperClusterKey,
                                    @RequestParam String connectString,
                                    @RequestParam(required = false) String description)
            throws RuntimeException {
        //assertIsPermitted(PermissionKeys.registryCenterAddZkCluster);
        zooKeeperService.updateZkCluster(zooKeeperClusterKey, connectString, description);
        return new Response();
    }

    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    //@Audit
    @PutMapping(value = "/zkClusters/deleteZooKeeperClusterInfo")
    public Response deleteZooKeeperClusterInfo(@RequestParam String zkClusterKey)
            throws RuntimeException {
        //assertIsPermitted(PermissionKeys.registryCenterRemoveZkCluster);
        zooKeeperService.deleteZooKeeperClusterInfo(zkClusterKey);
        return new Response();
    }

    /**
     * 获取单个或所有zk集群信息
     */
    //@ApiResponses(value = {@ApiResponse(code = 200, message = "Success/Fail", response = RequestResult.class)})
    @GetMapping(value = "/getZooKeeperCluster")
    public Response getZooKeeperCluster(@RequestParam(required = false) String status,
                                        @RequestParam(required = false) String zkClusterKey) throws RuntimeException {
        if (StringUtils.isNotBlank(zkClusterKey)) {
            ZooKeeperCluster zooKeeperCluster = zooKeeperService.getZooKeeperCluster(zkClusterKey);
            if (zooKeeperCluster == null) {
                throw new RuntimeException(
                        String.format("ZK cluster[%s]不存在", zkClusterKey));
            }
            return Response.success(zooKeeperCluster);
        }

        List<ZooKeeperCluster> zooKeeperClusterList = zooKeeperService.getZooKeeperClusterList();
        if (StringUtils.isBlank(status) || !"online".equals(status)) {
            return Response.success(zooKeeperClusterList);
        }

        List<ZooKeeperCluster> onlineZkCluster = filterOnlineZkClusters(zooKeeperClusterList);
        return Response.success(onlineZkCluster);
    }

    private List<ZooKeeperCluster> filterOnlineZkClusters(List<ZooKeeperCluster> zooKeeperClusterList) {
        if (zooKeeperClusterList == null) {
            return Lists.newLinkedList();
        }

        List<ZooKeeperCluster> list = Lists.newLinkedList();
        for (ZooKeeperCluster zooKeeperCluster : zooKeeperClusterList) {
            if (!zooKeeperCluster.isOffline()) {
                list.add(zooKeeperCluster);
            }
        }
        return list;
    }

}
